package com.boarsoft.boar.auth;

import com.boarsoft.bean.LogonI;
import com.boarsoft.common.Util;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginCheckFilter implements Filter {
	private String login;
	private String uncheck;

	public void init(FilterConfig config) throws ServletException {
		this.login = config.getInitParameter("login");
		this.uncheck = config.getInitParameter("uncheck");
		if ((this.login == null) || ("".equals(this.login))) {
			this.login = "/auth/login/index.html";
		}
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		HttpSession ses = req.getSession();
		String uri = req.getRequestURI();
		String ctx = req.getContextPath();
		if (uri.startsWith(ctx)) {
			uri = uri.substring(ctx.length());
		}
		LogonI<?> logon = (LogonI<?>) ses.getAttribute("logon");
		String[] aa = this.uncheck.split(",");
		if ((Util.inArray(uri, aa) > -1) || (logon != null)) {
			chain.doFilter(request, response);
		} else {
			PrintWriter out = res.getWriter();
//			out.print("<script language=\"javascript\">location='http");
//			String p = req.getProtocol();
//			if ((p != null) && (p.toLowerCase().startsWith("https"))) {
//				out.println("s");
//			}
//			out.print("://");
//			out.print(request.getServerName());
//			out.print(":");
//			out.print(request.getServerPort());
//			out.print(req.getContextPath() + this.login);
//			out.print("'</script>");
			out.print("<script language=\"javascript\">location='");
			out.print(this.login);
			out.print("'</script>");
			out.flush();
		}
	}

	public void destroy() {
	}
}
